﻿using System;
using System.Management.Automation;
using ITSP.SharePoint.CacheRefresh.Interfaces;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.PowerShell;

namespace ITSP.SharePoint.CacheRefresh.PowerShell
{
    /// <summary>
    /// Runs the Cache Refresh Job for a particular Cache Configuration Item
    /// </summary>
    [Cmdlet("Start", "ITSPCacheRefreshJob", SupportsShouldProcess = true)]
    public class StartCacheRefreshJob : SPCmdlet
    {
        #region Cmdlet Parameters
        [Parameter(Mandatory = true, HelpMessage = "The Url of the SharePoint Web Application that is hosting the Cache Configuration List")]
        public string Url;

        [Parameter(Mandatory = true, HelpMessage = "The Key of the Cache Configuration Item to run.")]
        public string CacheKey;

        #endregion

        protected override bool RequireUserFarmAdmin()
        {
            return false;
        }

        protected override bool RequireLocalFarmExist()
        {
            return true;
        }

        /// <summary>
        /// Executes the Cmdlet, running the specified Cache Refresh Timer Job.
        /// </summary>
        protected override void InternalProcessRecord()
        {
            #region validation stuff

            // ensure can hit farm
            SPFarm farm = SPFarm.Local;
            if (farm == null)
            {
                ThrowTerminatingError(new InvalidOperationException("SharePoint farm not found."), ErrorCategory.ResourceUnavailable, this);
                SkipProcessCurrentRecord();
            }

            #endregion

            string cacheHostUrl = Url;

            Uri cacheHostUri = new Uri(cacheHostUrl);

            using (SPSite site = new SPSite(cacheHostUri.ToString()))
            {
                if (!site.RootWeb.Exists)
                {
                    WriteObject(String.Format("Cannot find SPWeb at {0}", cacheHostUri.LocalPath));
                }

                try
                {
                    ICacheRefreshManager cacheRefreshManager = new CacheRefreshManager(cacheHostUri.ToString());
                    if (cacheRefreshManager.InvalidateCache(CacheKey))
                    {
                        WriteResult(String.Format("Successfully Run Cache Refresh Job {0}", CacheKey));
                    }
                    else
                    {
                        WriteResult(String.Format("Failed to Run Cache Refresh Job {0}", CacheKey));
                    }
                }
                catch (Exception ex)
                {
                    ThrowTerminatingError(ex, ErrorCategory.NotSpecified, this);
                }
                
                

            }


        }

    }
}
